package org.edu.eece262.taskshare;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;

public class TaskShare extends Activity {

	// Constants
	private static final int EDIT_TASK = 0xBADFAD;
	private static final int CREATE_SUBTASK = 0xFADBAD;
	private static final int REASSIGN_TASK = 0xC0FFEE;
	private static final int SORT_DUE = Menu.FIRST;
	private static final int SORT_PRIORITY = Menu.FIRST + 1;

	// Member Variables
	Button bAddTask = null;
	EditText etNewTask = null;
	TaskView tvMainList;
	String sortMethod = "";

	TaskDBAdapter tsdbAdapter;
	
	int currentTask;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		tsdbAdapter = TaskDBAdapter.getTSDBAdapter(getApplicationContext());
		tsdbAdapter.open();

		bAddTask = (Button) findViewById(R.id.bAddTask);
		etNewTask = (EditText) findViewById(R.id.etNewTask);
		tvMainList = new TaskView(getApplicationContext(), this);
		((ScrollView) findViewById(R.id.svListContainer)).addView(tvMainList);

		getTasks();

		bAddTask.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!etNewTask.getText().toString().equalsIgnoreCase("")) {

					if (tsdbAdapter.insertEntry(etNewTask.getText().toString(), 
							getIntent().getStringExtra("Username"),
							"", "", 0,
							0, 0, 0, 0, 2, getApplicationContext()) > 0) {
						makeToast("Task created successfully.");
					} else {
						makeToast("Task creation failed.");
					}
					tvMainList.update(getApplicationContext());
					tvMainList.invalidate();
					etNewTask.setText("");
				}
			}
		});

	}

	private void getTasks() {
		tvMainList.updateSorted(getApplicationContext(), sortMethod);
		tvMainList.invalidate();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, 1, 0, R.string.sort_due);
		menu.add(1, 2, 1, R.string.sort_priority);
		return result;
	}

	public void EditTask(int local_id) {
		Cursor c = tsdbAdapter.getTaskWithLocalID(local_id);
		c.moveToFirst();
		startActivityForResult(new Intent(getApplicationContext(),
				TaskEditor.class)
				.putExtra(TaskDBAdapter.DB_KEY_ID, c.getInt(0)).putExtra(
						TaskDBAdapter.KEY_GLOBAL_ID,
						c.getLong(TaskDBAdapter.GLOBAL_ID_COLUMN)).putExtra(
						TaskDBAdapter.KEY_NAME,
						c.getString(TaskDBAdapter.NAME_COLUMN)).putExtra(
						TaskDBAdapter.KEY_NOTES,
						c.getString(TaskDBAdapter.NOTES_COLUMN)).putExtra(
						TaskDBAdapter.KEY_LOCATION,
						c.getString(TaskDBAdapter.LOCATION_COLUMN)).putExtra(
						TaskDBAdapter.KEY_PARENT_LOCAL,
						c.getInt(TaskDBAdapter.PARENT_LOCAL_COLUMN)).putExtra(
						TaskDBAdapter.KEY_PARENT_GLOBAL,
						c.getInt(TaskDBAdapter.PARENT_GLOBAL_COLUMN)).putExtra(
						TaskDBAdapter.KEY_DUE_DATE,
						c.getInt(TaskDBAdapter.DUE_DATE_COLUMN)).putExtra(
						TaskDBAdapter.KEY_DUE_TIME,
						c.getInt(TaskDBAdapter.DUE_TIME_COLUMN)).putExtra(
						TaskDBAdapter.KEY_PERCENT_COMPLETE,
						c.getInt(TaskDBAdapter.PERCENT_COMPLETE_COLUMN))
				.putExtra(TaskDBAdapter.KEY_PRIORITY,
						c.getInt(TaskDBAdapter.PRIORITY_COLUMN)).putExtra(
						"Username", getIntent().getStringExtra("Username")),
				EDIT_TASK);
	}

	public void Reassign(int local_id) {
		dismissDialog(local_id);
		currentTask = local_id;
		startActivityForResult(new Intent(getApplicationContext(),ReassignTask.class)
		.putExtra("local_id", local_id), REASSIGN_TASK);
	}

	public void CreateSubtask(int local_id) {
		dismissDialog(local_id);
		currentTask = local_id;
		showDialog(0);
	}
	
	public void Selected(int local_id) {
		showDialog(local_id);
	}
	
	public void DeleteTask(int local_id) {
		Cursor task = TaskDBAdapter.getTSDBAdapter(getApplicationContext()).getTaskWithLocalID(local_id);
		task.moveToFirst();
		reassign_children(task.getInt(TaskDBAdapter.GLOBAL_ID_COLUMN), local_id, task.getInt(TaskDBAdapter.PARENT_GLOBAL_COLUMN), task.getInt(TaskDBAdapter.PARENT_LOCAL_COLUMN));
		TaskDBAdapter.getTSDBAdapter(getApplicationContext()).removeEntry(
				local_id, getApplicationContext());
		tvMainList.update(getApplicationContext());
		tvMainList.invalidate();
	}
	
	private void reassign_children(long globalId, int oldParentLocal,
			long parentGlobal, int newParentLocal) {
		Cursor children = TaskDBAdapter.getTSDBAdapter(getApplicationContext())
				.getChildrenOf(oldParentLocal);
		int count = children.getCount();
		if (count > 0) {
			children.moveToFirst();
			while (!children.isAfterLast()) {
				TaskDBAdapter
						.getTSDBAdapter(getApplicationContext())
						.changeParent(
								children
										.getInt(children
												.getColumnIndex(TaskDBAdapter.DB_KEY_ID)),
								newParentLocal, parentGlobal);
				children.moveToNext();
			}
		}

	}

	protected Dialog onCreateDialog(final int id) {
		if (id == 0) {
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			final EditText tmp;
			builder.setMessage("   Create Subtask   ")
			.setView(tmp = new EditText(getApplicationContext()))
			.setPositiveButton("Create", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							if (tmp.getText().toString().equalsIgnoreCase(""))
							{
								makeToast("Tasks must have names.");
							} else {
								Cursor c = tsdbAdapter.getTaskWithLocalID(currentTask);
								c.moveToFirst();
								if(TaskDBAdapter.getTSDBAdapter(
										getApplicationContext()).insertEntry(tmp.getText().toString(), 
												getIntent().getStringExtra("Username"), "", "", currentTask, 
												c.getLong(TaskDBAdapter.GLOBAL_ID_COLUMN), c.getInt(TaskDBAdapter.DUE_DATE_COLUMN), 
												c.getInt(TaskDBAdapter.DUE_TIME_COLUMN), 0, c.getInt(TaskDBAdapter.PRIORITY_COLUMN), 
												getApplicationContext()) > 0) {
									makeToast("Subtask created successfully.");
									getTasks();
									tmp.setText("");
									dialog.dismiss();
								} else {
									makeToast("Subtask creation failed.");
									getTasks();
									dialog.dismiss();
								}
							}
						}
					}).setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
						}
					});
			AlertDialog alert = builder.create();
			return alert;
		} else {
			LayoutInflater inflater = (LayoutInflater) getApplicationContext()
					.getSystemService(LAYOUT_INFLATER_SERVICE);

			View layout = inflater.inflate(R.layout.taskoptions,
					(ViewGroup) findViewById(R.id.toRoot));

			Button bEditTask = (Button) layout.findViewById(R.id.bEditTask);
			Button bReassignTask = (Button) layout
					.findViewById(R.id.bReassignTask);
			Button bNewSubtask = (Button) layout.findViewById(R.id.bNewSubtask);
			Button bDeleteTask = (Button) layout.findViewById(R.id.bDeleteTask);

			bEditTask.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					EditTask(id);
					dismissDialog(id);
				}
			});

			bReassignTask.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Reassign(id);
					dismissDialog(id);
				}
			});

			bNewSubtask.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					CreateSubtask(id);
					dismissDialog(id);
				}
			});
			
			bDeleteTask.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					DeleteTask(id);
					dismissDialog(id);
				}
			});

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("     Task Options     ").setView(layout)
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.dismiss();
								}
							});
			AlertDialog alert = builder.create();
			return alert;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case SORT_DUE:
			sortMethod = "due";
			getTasks();
			return true;
		case SORT_PRIORITY:
			sortMethod = "priority";
			getTasks();
			return true;
		default:

		}

		return super.onOptionsItemSelected(item);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == EDIT_TASK) {
			if (resultCode == RESULT_OK) {
				// Moved insert into TaskEditor before returning here.
				getTasks();
			}
		} else if (requestCode == CREATE_SUBTASK) {
			if (resultCode == RESULT_OK) {
				getTasks();
			}
		}
	}

	void makeToast(String alert) {
		Toast.makeText(getApplicationContext(), alert, Toast.LENGTH_SHORT)
				.show();
	}
}